/**
 * There are <a href="https://github.com/thinkgem/jeesite">JeeSite</a> code generation
 */
package com.boxin.ims.modules.wechat.web;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.boxin.framework.base.utils.DateUtils;
import com.boxin.ims.modules.sys.utils.RandomUtils;
import com.boxin.ims.modules.wechat.entity.Lottery;
import com.boxin.ims.modules.wechat.entity.LotteryConfig;
import com.boxin.ims.modules.wechat.entity.LotteryRecord;
import com.boxin.ims.modules.wechat.entity.WechatMember;
import com.boxin.ims.modules.wechat.service.LotteryConfigService;
import com.boxin.ims.modules.wechat.service.LotteryRecordService;
import com.boxin.ims.modules.wechat.service.LotteryService;
import com.boxin.ims.modules.wechat.service.WechatDaoHelper;
import com.boxin.ims.modules.wechat.service.WechatMemberService;
import com.boxin.ims.modules.wechat.utils.WechatUtils;
import com.google.common.collect.Maps;
import com.thinkgem.jeesite.common.config.Global;
import com.thinkgem.jeesite.common.persistence.Page;
import com.thinkgem.jeesite.common.utils.FileUtils;
import com.thinkgem.jeesite.common.utils.StringUtils;
import com.thinkgem.jeesite.common.web.BaseController;
import com.thinkgem.jeesite.modules.sys.entity.User;
import com.thinkgem.jeesite.modules.sys.utils.UserUtils;

/**
 * 抽奖Controller
 * @author Jakemanse
 * @version 2013-09-23
 */
@Controller
@RequestMapping(value = Global.ADMIN_PATH+"/wechat/lottery")
public class LotteryController extends BaseController {
	
	private Logger logger = Logger.getLogger(LotteryController.class);

	@Autowired
	private LotteryService lotteryService;
	
	@Autowired
	private WechatDaoHelper wechatDaoHelper;
	
	@Autowired
	private WechatMemberService wechatMemberService;
	
	@Autowired
	private LotteryConfigService lotteryConfigService;
	
	@Autowired
	private LotteryRecordService lotteryRecordService;
	
	
	
	@ModelAttribute
	public Lottery get(@RequestParam(required=false) Long id) {
		if (id != null){
			return lotteryService.get(id);
		}else{
			return new Lottery();
		}
	}
	
	
	
	/**
	 * @author Jakemanse
	 * @time 2013-9-23  上午10:18:32
	 * @function <p> 进行抽奖的活动页面  </p>
	 * @param lottery
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequiresPermissions("wechat:lottery:view")
	@RequestMapping(value = "lottery")
	public String lottery(HttpServletRequest request, HttpServletResponse response, Model model,RedirectAttributes redirectAttributes) {
		
		User user = UserUtils.getUser();
		String id = request.getParameter("id");		//Lottery奖品的ID
		String clean = request.getParameter("clean");	
		String topage = request.getParameter("topage");	
		if("clean".equals(clean)){//清除队列
			Map<String,String> params = new HashMap<String,String>();
			params.put("day", com.boxin.framework.base.utils.DateUtils.getTodayString());
			params.put("userId", user.getId()+"");
			wechatDaoHelper.cleanLotteryQueue(params);
		}
		
		if(StringUtils.isEmpty(id)){
			redirectAttributes.addAttribute("请先设置您的抽奖品.");
			return "modules/wechat/lottery";
		}
		// 抽奖奖品
		Lottery lottery = lotteryService.get(Long.parseLong(id));
		String lotteryFlag = "1";	//1：可以抽奖  0：不可以
		int persons = 0;
		//今天的绑定会员
		String day = DateUtils.getTodayString();
		Map<String, String> params = new HashMap<String,String>();
		params.put("day", day);
		params.put("userId", ""+UserUtils.getUser().getId());
		List<Map<String,Object>> result = 	wechatDaoHelper.queryQueueMembers(params);
		StringBuffer sbmobiles = new StringBuffer();
		Set<String> mobileSet = new HashSet<String>();
		if(result!=null && !result.isEmpty()){
			if(result.size()<lottery.getPeramount()){
				addMessage(redirectAttributes, "参与抽奖人数还不足"+lottery.getPeramount()+"人,暂时不能进行抽奖活动.");
				lotteryFlag = "0";
			}else{
				
				for(Map<String,Object> map : result){
					mobileSet.add(map.get("mobile").toString());
					//if(mobileSet.contains(map.get("mobile").toString())) continue;		//不得有重复的手机号。
					
					//sbmobiles.append(map.get("mobile")).append(",");
				}
				//sbmobiles.deleteCharAt(sbmobiles.lastIndexOf(","));
			}
			
			persons = result.size();	//参与人数
		}else{
			addMessage(redirectAttributes, "参与抽奖人数还不足"+lottery.getPeramount()+"人,暂时不能进行抽奖活动.");
			lotteryFlag = "0";
		}
		
		//获得店家的奖品列表
		List<Lottery>lotteryList = lotteryService.findSellerLotteryListByUserId(user.getId());
		
		for(String mobile:mobileSet){
			sbmobiles.append(mobile).append(",");
		}
		
		if(sbmobiles.lastIndexOf(",")>0) sbmobiles.deleteCharAt(sbmobiles.lastIndexOf(","));
		
		model.addAttribute("alldata",sbmobiles.toString() );
        model.addAttribute("lottery", lottery);
        model.addAttribute("lotteryList", lotteryList);
        model.addAttribute("mobileList", result);
        model.addAttribute("persons", persons);
        
        model.addAttribute("lotteryFlag", lotteryFlag);
        
        
        if("eggs".equals(topage)){
        	return eggSceneLottery(lottery,request,response,model);
        }
        
		return "modules/wechat/lottery";
	}
	
	
	/**
	 * @author Jakemanse
	 * @time 2013-12-6  下午2:55:51
	 * @function <p> 管理员设定奖品  </p>
	 * @param request
	 * @param response
	 * @param model
	 * @param redirectAttributes
	 * @return
	 */
	@RequestMapping(value = "alottery")
	public String doAdminLottery(  HttpServletRequest request, HttpServletResponse response, Model model,RedirectAttributes redirectAttributes) {
		
		try {
			String mobile = request.getParameter("mobile");	//用 ，分隔
			String id = request.getParameter("id");
			String uname = request.getParameter("uname");
			
			Lottery lottery = null;
			lottery = lotteryService.get(Long.parseLong(id));
			User user = UserUtils.getUserByUsername(uname);
			if(user!=null && lottery !=null){
				WechatMember member =	wechatMemberService.getByWechatMobile(user, mobile);
				
				if(member!=null){
					LotteryConfig config = lotteryConfigService.getByUserId(user.getId());
					
					LotteryRecord lotteryRecord = new LotteryRecord();
					lotteryRecord.setUser(user);
					lotteryRecord.setLottery(lottery);
					lotteryRecord.setMember(member);
					lotteryRecord.setStatus(LotteryRecord.STATUS_NORMAL);
					lotteryRecord.setSourceType(LotteryRecord.SOURCE_TYPE_ME);
					lotteryRecord.setScope(LotteryRecord.SCOPE_NEW);
					lotteryRecord.setEndTime(com.boxin.framework.base.utils.DateUtils.getDelayDate(config.getValidDays()));
					lotteryRecord.setName(lottery.getName());
					
					lotteryRecordService.save(lotteryRecord);
					
					response.getWriter().print("抽奖成功，恭喜您抽中了‘"+lottery.getName()+"’.");
					
				}else{
					response.getWriter().print("未找到商家‘"+user.getName()+"’下手机号为["+mobile+"]的会员.");
				}
			}else{
				response.getWriter().print("未找到对应的商家或奖品。");
			}
		} catch (Exception e) {
			e.printStackTrace();
			try {
				response.getWriter().print("处理失败："+e.getMessage());
			} catch (Exception e2) {
			}
		}
		
		
		return null;
	}
	 
	
	
	
	/**
	 * @author Jakemanse
	 * @time 2013-10-5  下午10:44:02
	 * @function <p> 店家抽奖中奖处理。 </p>
	 * @param request
	 * @param response
	 * @param model
	 * @param redirectAttributes
	 * @return
	 */
	@RequestMapping(value = "dolottery")
	public String doLottery(  HttpServletRequest request, HttpServletResponse response, Model model,RedirectAttributes redirectAttributes) {
		String mobile = request.getParameter("mobile");	//用 ，分隔
//		if(request.getParameter("jakemanse").equals("jakemanse")){
//			mobile="13503106916,15133001302,15081732785,18231076929,15132088008,13785056189,13739605063,15081639901,15230033309,15930008899";
//		}
		logger.debug("本次商家抽奖中奖的用户有:"+mobile);
		User user = UserUtils.getUser();
		String id = request.getParameter("id");	//用 ，分隔
		String mobiles[] = mobile.split(",");
		logger.debug("本次中奖的号码为:"+mobile);
		Map params = Maps.newTreeMap();
		Lottery lottery = null;
		if(StringUtils.isEmpty(id) ){
			model.addAttribute("message", "未找对应的奖品信息，抽奖前请先确认已设置好奖品的配置，谢谢！");
			params.put("isSuccess", false);
			params.put("errorInfo", "未找对应的奖品信息，抽奖前请先确认已设置好奖品的配置，谢谢！");
			responseJson(request, response, params);
			return null;
		}else{
			lottery = lotteryService.get(Long.parseLong(id));
		}
		
		
		List<LotteryRecord> lotteryList = new ArrayList<LotteryRecord>();
		LotteryConfig config = lotteryConfigService.getByUserId(user.getId());
		
		for(String m:mobiles){
			
			WechatMember member =	wechatMemberService.getByWechatMobile(user, m);
//			
			
			LotteryRecord lotteryRecord = new LotteryRecord();
			lotteryRecord.setUser(user);
			lotteryRecord.setLottery(lottery);
			lotteryRecord.setMember(member);
			lotteryRecord.setStatus(LotteryRecord.STATUS_NORMAL);
			lotteryRecord.setSourceType(LotteryRecord.SOURCE_TYPE_SELLER);
			lotteryRecord.setScope(LotteryRecord.SCOPE_NEW);
			lotteryRecord.setEndTime(com.boxin.framework.base.utils.DateUtils.getDelayDate(config.getValidDays()));
			lotteryRecord.setName(lottery.getName());
			
			lotteryRecordService.save(lotteryRecord);
			
			lotteryList.add(lotteryRecord);
		}
		
		if(lotteryList.size()>0){
			
			//抽奖完毕后 清除抽奖队列表
			Map<String,String> params2 = new HashMap<String,String>();
			params2.put("day", com.boxin.framework.base.utils.DateUtils.getTodayString());
			params2.put("userId", user.getId()+"");
			
			if(config.isCleanQueue()){//根据配置
				
				wechatDaoHelper.cleanLotteryQueue(params2);
			}
			
			//清除本轮已经中奖的会员 
			String inSql = StringUtils.convertToInSQL(mobiles);
			params2.put("mobiles", inSql);
			wechatDaoHelper.cleanLotteryQueueByMobiles(params2);
			
			
			params2.put("isSuccess", "true");
			params2.put("errorInfo", "");
			responseJson(request, response, params2);
		}else{
			
			params.put("isSuccess", true);
			params.put("errorInfo", "未找到对应的中奖号码!");
			responseJson(request, response, params);
		}
		
		model.addAttribute("lotteryList", lotteryList);
		
		
		return null;
	}
	
	
	
	
	@RequiresPermissions("wechat:lottery:view")
	@RequestMapping(value = {"list",""})
	public String list(Lottery lottery, HttpServletRequest request, HttpServletResponse response, Model model) {
		User user = UserUtils.getUser();
		if (!user.isAdmin()){
			lottery.setUser(user);
		}
		
		Page<Lottery> page = lotteryService.find(new Page<Lottery>(request, response), lottery); 
		model.addAttribute("page", page);
		model.addAttribute("user", user);
		return "modules/wechat/lotteryList";
	}
	
	/**
	 * @author Jakemanse
	 * @time 2013-10-5  下午11:17:26
	 * @function <p> 现场抽奖列表 </p>
	 * @param lottery
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequiresPermissions("wechat:lottery:view")
	@RequestMapping(value = "scene")
	public String sceneLottery(Lottery lottery, HttpServletRequest request, HttpServletResponse response, Model model) {
		User user = UserUtils.getUser();
		if (!user.isAdmin()){
			lottery.setUser(user);
		}
		lottery.setType(Lottery.LOTTERY_TYPE_SELLER);
		
		Page<Lottery> page = lotteryService.find(new Page<Lottery>(request, response), lottery); 
		model.addAttribute("page", page);
		return "modules/wechat/sceneLotteryList";
	}
	
	
	/**
	 * @author Jakemanse
	 * @time 2014-4-24  上午11:19:30
	 * @function <p>现场砸金蛋抽奖 列表 </p>
	 * @param lottery
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequiresPermissions("wechat:lottery:view")
	@RequestMapping(value = "toEggScene")
	public String eggSceneLottery(Lottery lottery, HttpServletRequest request, HttpServletResponse response, Model model) {
		User user = UserUtils.getUser();
		if (!user.isAdmin()){
			lottery.setUser(user);
		}
		lottery.setType(Lottery.LOTTERY_TYPE_SELLER);
		
		Page<Lottery> page = lotteryService.find(new Page<Lottery>(request, response), lottery); 
		model.addAttribute("page", page);
		return "modules/wechat/lottery/eggs/eggsSceneLotteryList";
	}
	
	
	/**
	 * @author Jakemanse
	 * @time 2014-4-24  下午3:28:51
	 * @function <p> 砸金蛋页面 </p>
	 * @param lottery
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequiresPermissions("wechat:lottery:view")
	@RequestMapping(value = "toEggLottery")
	public String toEggLottery(Lottery lottery,Long id, HttpServletRequest request, HttpServletResponse response, Model model) {
		User user = UserUtils.getUser();
		if (!user.isAdmin()){
			lottery.setUser(user);
		}
		lottery.setType(Lottery.LOTTERY_TYPE_SELLER);
		lottery.setId(id);
		
		Page<Lottery> page = lotteryService.find(new Page<Lottery>(request, response), lottery); 
		
		String day = DateUtils.getTodayString();
		Map<String, String> params = new HashMap<String,String>();
		params.put("day", day);
		params.put("userId", ""+UserUtils.getUser().getId());
		List<Map<String,Object>> members  = 	wechatDaoHelper.queryQueueMembers(params);
		if(members.size()<lottery.getPeramount()){
			model.addAttribute("lotteryFlag", "0");
		}
		
		model.addAttribute("page", page);
		model.addAttribute("lottery", lottery);
		model.addAttribute("persons", members.size());
		
		
		return "modules/wechat/lottery/eggs/index";
	}
	
	
	
	/**
	 * @author Jakemanse
	 * @time 2014-4-24  下午5:13:36
	 * @function <p> 查询当前队人数 </p>
	 * @param lotteryId
	 * @param userId
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequiresPermissions("wechat:lottery:view")
	@RequestMapping(value = "queryLotteryQueue")
	public String queryLotteryQueue(Long userId, HttpServletRequest request, HttpServletResponse response, Model model) {
		
		//2.随机找人
		String day = DateUtils.getTodayString();
		Map<String, String> params = new HashMap<String,String>();
		params.put("day", day);
		params.put("userId", ""+userId);
		List<Map<String,Object>> members  = 	wechatDaoHelper.queryQueueMembers(params);		
		
		Map<String,String> resMap = new HashMap<String,String>();
		resMap.put("persons", members.size()+"");
		
		writeJson(request, response, resMap);
		
				
		return null;
	}
	
	
	
	
	/**
	 * @author Jakemanse
	 * @time 2014-4-24  上午11:29:51
	 * @function <p> 砸金蛋 中奖处理 </p>
	 * @param lottery
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequiresPermissions("wechat:lottery:view")
	@RequestMapping(value = "doEggsLottery")
	public String doEggsLottery(Long lotteryId,Long userId, HttpServletRequest request, HttpServletResponse response, Model model) {
		
		
		//1.确定奖品
		Lottery lottery = lotteryService.get(lotteryId);
		LotteryConfig config = lotteryConfigService.getByUserId(userId);
		//2.随机找人
		String day = DateUtils.getTodayString();
		Map<String, String> params = new HashMap<String,String>();
		params.put("day", day);
		params.put("userId", ""+UserUtils.getUser().getId());
		List<Map<String,Object>> members  = 	wechatDaoHelper.queryQueueMembers(params);
		
		int randIndex = RandomUtils.randArrayInt(members.size());
		
		Map<String,Object> map =(members!=null && !members.isEmpty())? members.get(randIndex):null;
		
		Map<String,String> resMap = new HashMap<String,String>();
		if(map!=null && !map.isEmpty()){
			Long memberId = Long.parseLong(map.get("member_id").toString()); 
			
			User user = UserUtils.getUserById(userId);
			WechatMember member = wechatMemberService.get(memberId);
			resMap.put("lotteryName", lottery.getName());
			resMap.put("memberName", member.getName());
			resMap.put("memberMobile", member.getMobile());
			resMap.put("userId", userId.toString());
			resMap.put("success", "1");
			
			//生成奖品
			LotteryRecord record = new LotteryRecord();
			record.setName(lottery.getName());
			record.setMember(member);
			record.setUser(user);
			record.setSourceType(LotteryRecord.SURCE_TYPE_EGG);
			record.setStatus(LotteryRecord.STATUS_NORMAL);
			record.setValid(true);
			record.setEndTime(DateUtils.getDelayDate(config.getValidDays()));
			
			lotteryRecordService.save(record);
			
			//中奖日志
			
			
			
			//清除队列
			//抽奖完毕后 清除抽奖队列表
			Map<String,String> params2 = new HashMap<String,String>();
			params2.put("day", com.boxin.framework.base.utils.DateUtils.getTodayString());
			params2.put("userId", user.getId()+"");
			
			if(config.isCleanQueue()){//根据配置
				
				wechatDaoHelper.cleanLotteryQueue(params2);
			}
			
			//清除本轮已经中奖的会员 
			String mobiles[] = new String[1];
			mobiles[0] = member.getMobile();
			
			String inSql = StringUtils.convertToInSQL(mobiles);
			params2.put("mobiles", inSql);
			wechatDaoHelper.cleanLotteryQueueByMobiles(params2);
			
			
			
			//写JSON
			writeJson(request, response, resMap);
			
		}else{
			resMap.put("success", "0");
			writeJson(request, response, resMap);
			
		}
		
		
		return null;
	}
	
	
	
	
	
	
	
	
	
	
	
	
	
	/**
	 * @author Jakemanse
	 * @time 2013-10-7  下午11:11:14
	 * @function <p>  </p>
	 * @param request
	 * @param response
	 * @param model
	 * @param redirectAttributes
	 * @return
	 */
	@RequestMapping(value = "droplottery")
	public String dropLottery(  HttpServletRequest request, HttpServletResponse response, Model model,RedirectAttributes redirectAttributes) {
		String mobile = request.getParameter("mobile");	//用 ，分隔
		String id = request.getParameter("id");	//用 ，分隔
		String mobiles[] = mobile.split(",");
		Map params = Maps.newTreeMap();
		Lottery lottery = null;
		if(StringUtils.isEmpty(id) ){
			model.addAttribute("message", "未找对应的奖品信息，抽奖前请先确认已设置好奖品的配置，谢谢！");
			params.put("isSuccess", false);
			params.put("errorInfo", "未找对应的奖品信息，抽奖前请先确认已设置好奖品的配置，谢谢！");
			responseJson(request, response, params);
			return null;
		}else{
			lottery = lotteryService.get(Long.parseLong(id));
		}
		
		
		return null;
	}
	

	@RequiresPermissions("wechat:lottery:view")
	@RequestMapping(value = "form")
	public String form(Lottery lottery, Model model) {
		User user = UserUtils.getUser();
		lottery.setUser(user);
		model.addAttribute("lottery", lottery);
		return "modules/wechat/lotteryForm";
	}
	

	@RequiresPermissions("wechat:lottery:edit")
	@RequestMapping(value = "save")
	public String save(HttpServletRequest request,Lottery lottery, Model model, RedirectAttributes redirectAttributes) {
		if (!beanValidator(model, lottery)){
			return form(lottery, model);
		}
		lottery.setScore((int)(Double.parseDouble(request.getParameter("pScore"))*1000));
		lotteryService.save(lottery);
		addMessage(redirectAttributes, "保存抽奖'" + lottery.getName() + "'成功");
		return "redirect:"+Global.ADMIN_PATH+"/wechat/lottery/?repage";
	}
	
	@RequiresPermissions("wechat:lottery:edit")
	@RequestMapping(value = "delete")
	public String delete(Long id, RedirectAttributes redirectAttributes) {
		lotteryService.delete(id);
		addMessage(redirectAttributes, "删除抽奖成功");
		return "redirect:"+Global.ADMIN_PATH+"/wechat/lottery/?repage";
	}
	
	/*    --------------------------下面是活动奖品的设置----------------------------------------------------------*/
	
	/**
	 * 为了添加活动处理器的奖品
	 *@author xiaoqian
	 * @param lottery
	 * @param model
	 * @return
	 * 2014-4-11上午11:07:08
	 */
	@RequiresPermissions("wechat:lottery:view")
	@RequestMapping(value = "activityForm")
	public String activityForm(Lottery lottery, Model model) {
		User user = UserUtils.getUser();
		lottery.setUser(user);
		model.addAttribute("lottery", lottery);
		return "modules/wechat/activity/lotteryForm";
	}
	
	/**
	 * 活动处理器奖品列表
	 *@author xiaoqian
	 * @param lottery
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 * 2014-4-11上午11:24:50
	 */
	@RequiresPermissions("wechat:lottery:view")
	@RequestMapping(value = "activityList")
	public String activityList(Lottery lottery, HttpServletRequest request, HttpServletResponse response, Model model) {
		User user = UserUtils.getUser();
		if (!user.isAdmin()){
			lottery.setUser(user);
		}
		lottery.setType("4");
		Page<Lottery> page = lotteryService.find(new Page<Lottery>(request, response), lottery); 
		model.addAttribute("page", page);
		model.addAttribute("user", user);
		return "modules/wechat/activity/lotteryList";
	}
	
	
	
	/* 三级推广 */
//	@RequiresPermissions("wechat:lottery:view")
	@RequestMapping(value = "expandLotteryList")
	public String expandLotteryList(Lottery lottery, HttpServletRequest request, HttpServletResponse response, Model model) {
		User user = UserUtils.getUser();
		if (!user.isAdmin()){
			lottery.setUser(user);
		}
		Page<Lottery> page = lotteryService.expandFind(new Page<Lottery>(request, response), lottery); 
		model.addAttribute("page", page);
		model.addAttribute("user", user);
		return "modules/wechat/expandLotteryList";
	}
	
//	@RequiresPermissions("wechat:lottery:view")
	@RequestMapping(value = "expandLotteryForm")
	public String expandLotteryForm(Lottery lottery, Model model) {
		User user = UserUtils.getUser();
		lottery.setUser(user);
		model.addAttribute("lottery", lottery);
		return "modules/wechat/expandLotteryForm";
	}
	
//	@RequiresPermissions("wechat:lottery:edit")
	@RequestMapping(value = "expandLotterySave")
	public String expandLotterySave(@RequestParam("diancanPicFile") MultipartFile signPicFile,HttpServletRequest request,Lottery lottery, Model model, RedirectAttributes redirectAttributes) {
		if (!beanValidator(model, lottery)){
			return form(lottery, model);
		}
		if(signPicFile != null && signPicFile.getOriginalFilename().length()>4){
			String regMemberPicPath = WechatUtils.getWechatRegMemberSavePath(request)+File.separator;
			FileUtils.createDirectory(regMemberPicPath);
			String sname = signPicFile.getOriginalFilename();
			String fileType = sname.substring(sname.lastIndexOf("."));
			String fname  = UserUtils.getUser().getLoginName()+	"_hongbao_"+System.currentTimeMillis()+fileType;
			File file = new File(regMemberPicPath+fname);
			System.out.println("保存文件:"+regMemberPicPath+fname);
			try {
				signPicFile.transferTo(file);
				lottery.setPrizeimg(file.getName());
			} catch (Exception e) {
				System.out.println("上传文件失败:"+regMemberPicPath+fname);
				e.printStackTrace();
			}
		}		
		lotteryService.save(lottery);
		addMessage(redirectAttributes, "保存三级推广奖品'" + lottery.getName() + "'成功");
		return "redirect:"+Global.ADMIN_PATH+"/wechat/lottery/expandLotteryList?sourceId="+lottery.getSourceId()+"&sourceType=3&type=7";
	}
	
//	@RequiresPermissions("wechat:lottery:edit")
	@RequestMapping(value = "expandLotteryDelete")
	public String expandLotteryDelete(Long id, Long sourceId, RedirectAttributes redirectAttributes) {
		lotteryService.delete(id);
		addMessage(redirectAttributes, "删除三级推广奖品成功");
		return "redirect:"+Global.ADMIN_PATH+"/wechat/lottery/expandLotteryList?sourceId="+sourceId+"&sourceType=3&type=7";
	}
	
	
	
	/**
	 * 
	 *@author xiaoqian
	 * @param lottery
	 * @param model
	 * @param redirectAttributes
	 * @return
	 * 2014-4-11上午11:26:21
	 */
	@RequiresPermissions("wechat:lottery:edit")
	@RequestMapping(value = "activitySave")
	public String activitySave(Lottery lottery, Model model, RedirectAttributes redirectAttributes) {
		if (!beanValidator(model, lottery)){
			return form(lottery, model);
		}
		lotteryService.save(lottery);
		addMessage(redirectAttributes, "保存抽奖'" + lottery.getName() + "'成功");
		return "redirect:"+Global.ADMIN_PATH+"/wechat/lottery/activityList?repage";
	}

}
